package com.share.shareplatform.sharereward.controller;

import com.share.shareplatform.pojo.Goods;
import com.share.shareplatform.pojo.Provide;
import com.share.shareplatform.pojo.Reward;
import com.share.shareplatform.pojo.User;
import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.sharereward.service.RewardService;
import com.share.shareplatform.sharereward.service.feign.GoodsService;
import com.share.shareplatform.sharereward.service.feign.UserService;
import com.share.shareplatform.util.AuthorityUtil;
import com.share.shareplatform.util.Result;
import com.share.shareplatform.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import java.util.List;
import java.util.Map;

@RestController

@RequestMapping("/reward")
public class RewardController {

    @Autowired
    private RewardService rewardService;

    @Autowired
    private UserService userService;



    @PostMapping
    @PreAuthorize("hasAuthority('rewardAdd')")
    @ApiOperation(value = "悬赏令添加",notes = "必需字段：need,longitude,latitude\n可选字段：address,contact\n额外说明：如果是超级管理员：需要额外指定userId字段")
    public Result addOne( @RequestBody @Validated Reward reward) {
        if(reward.getLatitude()==null||reward.getLongitude()==null){
            throw new LogicException("经纬度不能为空");
        }

        //初始化
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId =AuthorityUtil.getUserId();
            reward.setUserId(userId);
        }else{
            if(reward.getUserId()==null){
                throw new LogicException("请指定用户id");
            }
        }
        Long flag = rewardService.addOne(reward);
        if(flag>0){
            return Result.getInstance(200,"添加成功");
        }
        throw new LogicException("添加失败");
    }
    @ApiOperation(value = "悬赏令修改",notes = "必需字段：id\n可选字段：need,contact\n")
    @PreAuthorize("hasAuthority('rewardUpdate')")
    @PutMapping
    public Result updateBaseOne(@RequestBody @Validated Reward reward) {
        if(reward.getId()==null){
            throw new LogicException("请指定id");
        }
        //查询旧的
        Reward oldReward = rewardService.findOneById(reward.getId());
        if(oldReward==null){
            throw new LogicException("该悬赏令不存在，无法修改");
        }
        //非管理员
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId =AuthorityUtil.getUserId();

            if (oldReward.getUserId()!=userId) {
                throw new LogicException("该悬赏令不不属于你，无法修改");
            }

        }

        Integer flag = rewardService.updateBaseOne(reward);
        if(flag>0){
            return Result.getInstance(200,"修改成功");
        }
        throw new LogicException("修改失败");

    }

    @ApiOperation(value = "悬赏令删除",notes = "其中ids为 'id-id-id' 这种类型的字符串")
    @PreAuthorize("hasAuthority('rewardDelete')")
    @DeleteMapping("/all/{ids}")
    public Result deleteAllByIds(@PathVariable("ids") String ids) {
        List<Long> list = StringUtils.splitStringToLongList(ids);

        if(!AuthorityUtil.hasAuthorityUtil("ROLE_admin")){
            List<Reward> rewardList = rewardService.findAllByIds(list);
            Long userId = AuthorityUtil.getUserId();
            for(Reward reward:rewardList){
                if(reward.getUserId()!=userId){
                    throw new LogicException("该悬赏令不属于你，无法删除");
                }
            }
        }
        Integer flag = rewardService.deleteAllByIds(list);
        return Result.getInstance(200,"删除了"+flag+"条数据");
    }


    @ApiOperation(value = "悬赏令分页查询",notes = "必需字段：pageIndex（第几页）,pageSize(每页大小)")
    @GetMapping("/page/{pageIndex}/{pageSize}")
    @PermitAll
    public Result findPage(@PathVariable("pageIndex") Integer pageIndex,@PathVariable("pageSize") Integer pageSize) {
        List<Reward> list = rewardService.findPage(pageIndex, pageSize);
        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value = "悬赏令查询,按id")
    @GetMapping("/{id}")
    @PermitAll
    public Result findOneById(@PathVariable("id") Long id) {
        Reward reward = rewardService.findOneById(id);
        if(reward==null){
            throw new LogicException("不存在");
        }
        return Result.getInstance(200,"success").put("reward",reward);
    }

    @GetMapping("/all/{ids}")
    @PermitAll
    @ApiOperation(value="批量查询，按id",notes = "其中ids为 'id-id-id' 这种类型的字符串")
    public Result findAllByIds(@PathVariable("ids") String ids) {
        List<Long> list = StringUtils.splitStringToLongList(ids);
        List<Reward> rewardList = rewardService.findAllByIds(list);
        return Result.getInstance(200,"success").put("list",rewardList);
    }

    @ApiOperation(value="查询，按userId")
    @PermitAll
    @GetMapping("all/userId/{id}")
    public Result findAllByUserId(@PathVariable("id") Long id) {
        List<Reward> list = rewardService.findAllByUserId(id);
        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value="查询已登录用户发布的悬赏令及其推送商品")
    @PermitAll
    @GetMapping("all/user/public")
    public Result findAllByUser() {
        Long userId = AuthorityUtil.getUserId();
        List<Reward> list = rewardService.findAllByUserId(userId);
        StringBuilder stringBuilder=new StringBuilder();
        for(Reward reward:list){
            for(Provide provide:reward.getProvideList()){
                stringBuilder.append(provide.getUserId()+"-");
            }
        }
        if(stringBuilder.length()!=0){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            Map<Long, User> map = Result.getMapResultValue(userService.findAllSafeByIdsAsMap(stringBuilder.toString()), Long.class, User.class);
            for(Reward reward:list){
                for(Provide provide:reward.getProvideList()){
                    provide.setUser(map.get(provide.getUserId()));
                }
            }
        }
        return Result.getInstance(200,"success").put("list",list);
    }




    @PermitAll
    @ApiOperation(value="按距离查询查询，按id",notes = "必需字段：longitude（纬度），latitude（经度）")
    @GetMapping("all/distance/{longitude}/{latitude}")
    public Result findAllByDistance(@PathVariable String latitude, @PathVariable String longitude) {
        Reward reward = new Reward();
        reward.setLatitude(Double.parseDouble(latitude));
        reward.setLongitude(Double.parseDouble(longitude));
        List<Reward> list = rewardService.findAllByDistance(reward);
        return Result.getInstance(200,"success").put("list",list);
    }


}
